掌握 高级控制流程 意味着超越线性执行,采用复杂的迭代模式和多路分支。通过整合 do-while 循环, switch 语句以及 break/continue 关键字,程序员可以精确地控制机器如何处理复杂逻辑。
1. for 循环的结构解析
这个 for 循环是一种结构化的迭代模式,包含三个不同部分: 初始化 (定义起始点), 检查 (条件表达式),以及 更新 (修改状态)。例如, for (var i = 0; i <= 12; i += 2) 展示了每次递增 2 的控制方式。
2. 中断执行
精准控制通过逻辑中断实现: break 语句会立即退出外层循环,而 continue 则跳过当前代码块的执行,直接进入下一次循环。取余运算符(%)在此处至关重要,用于判断是否可整除(例如, current % 7 == 0)。
do {
var yourName = prompt("你是谁?");
} while (!yourName);
var yourName = prompt("你是谁?");
} while (!yourName);
3. 多路分支
这个 switch 语句提供了比长串 if-else 链更简洁的替代方案,用于将多个离散值与单一表达式进行比较。
main.py
TERMINALbash — 80x24
> Ready. Click "Run" to execute.
>
QUESTION 1
What is unique about a
do loop compared to a while loop?It never executes if the condition is false.
It always executes its body at least once.
It is faster for mathematical calculations.
It automatically increments the counter.
✅ Correct!
Correct! A do-while loop executes the body first and only tests the stop condition afterward.❌ Incorrect
Incorrect. The do loop structure ensures the first run happens before the check.QUESTION 2
Which keyword immediately exits the current loop entirely?
continue
exit
break
return
✅ Correct!
The break statement jumps control immediately out of the enclosing loop.❌ Incorrect
The continue keyword only skips the current iteration, not the whole loop.QUESTION 3
Write a loop that makes seven calls to console.log to output a triangle of # characters. [Word Count Required: 50 words]
for(let line = '#'; line.length < 8; line += '#') console.log(line);
while(i < 7) { console.log('#'); }
✅ Correct!
Model Answer: To solve this, initialize a string variable with a single '#' character. In each iteration of a 'for' loop, check if the string's length is less than eight. Inside the body, log the string, then update it by appending another '#' until seven lines are printed successfully.❌ Incorrect
You must use the length of the string or a counter to increment the characters on each line.QUESTION 4
Write the 'FizzBuzz' program logic for numbers 1 to 100. [Word Count Required: 100 words]
Implementation using % 3, % 5, and % 15.
✅ Correct!
Model Answer: This program uses a 'for' loop to iterate from 1 to 100. Inside, we apply conditional branching. First, check if a number is divisible by both 3 and 5 using the remainder operator (n % 15 == 0) to print 'FizzBuzz'. If that fails, check if it is divisible by 3 for 'Fizz' or 5 for 'Buzz'. If none match, print the number itself. This logic demonstrates how order of operations in conditional branches is critical; checking for the combined 'FizzBuzz' case first prevents the program from incorrectly stopping at the simpler 'Fizz' or 'Buzz' conditions.❌ Incorrect
Ensure you check for the common multiple (15) first, otherwise 15 will only print 'Fizz'.QUESTION 5
Explain the logic to create an 8x8 checkerboard grid string. [Word Count Required: 150 words]
Nested loops with newline characters and a size variable.
✅ Correct!
Model Answer: To build an 8x8 checkerboard, we represent the grid using a single string and two nested 'for' loops. The outer loop handles the vertical rows (y-axis), while the inner loop handles the horizontal columns (x-axis). At each grid position (x, y), we decide whether to add a space or a '#' character. The mathematical trick is to check if the sum of the current x and y indices is even or odd: (x + y) % 2 == 0. If even, add a space; if odd, add '#'. After the inner loop completes a row, append a newline character ('\n') to start the next line. By defining a 'size' variable (e.g., size = 8) and using it as the loop limit for both x and y, the program becomes dynamic. This allows the user to generate a grid of any dimensions (e.g., 10x10 or 20x20) simply by changing one variable value.❌ Incorrect
Remember to use a nested loop structure and the modulo operator on the sum of indices to create the alternating pattern.Case Study: Modular Pattern Generation
Applying Control Flow to Structural Data
You are tasked with building a terminal-based UI component that generates a grid for a game. You must use modular arithmetic to determine tile patterns and a 'switch' statement to handle different terrain types ('grass', 'water', 'mountain').
Q
How would you modify a grid loop to only place a 'mountain' symbol every 7 tiles?
Solution:
Inside the loop, use the condition 'if (index % 7 == 0)'. This leverages the remainder operator to identify every seventh iteration regardless of the total grid size.
Inside the loop, use the condition 'if (index % 7 == 0)'. This leverages the remainder operator to identify every seventh iteration regardless of the total grid size.
Q
Why is a 'switch' better than 'if-else' for handling 5 different terrain types?
Solution:
A 'switch' statement is more readable for discrete values. It provides a structured 'default' case for error handling and avoids the visual clutter of repetitive 'else if' blocks, making the code easier for humans to scan.
A 'switch' statement is more readable for discrete values. It provides a structured 'default' case for error handling and avoids the visual clutter of repetitive 'else if' blocks, making the code easier for humans to scan.